package com.plusjun.gulimall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plusjun.common.utils.PageUtils;
import com.plusjun.common.utils.Query;
import com.plusjun.common.utils.R;
import com.plusjun.gulimall.ware.dao.WareInfoDao;
import com.plusjun.gulimall.ware.entity.WareInfoEntity;
import com.plusjun.gulimall.ware.feign.MemberFeignService;
import com.plusjun.gulimall.ware.service.WareInfoService;
import com.plusjun.gulimall.ware.vo.FareVO;
import com.plusjun.gulimall.ware.vo.MemberAddressVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Resource
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                new QueryWrapper<WareInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("name", key);
            });
        }
        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public FareVO getFare(Long addrId) {
        FareVO fareVO = new FareVO();
        R r = memberFeignService.info(addrId);
        MemberAddressVO data = (MemberAddressVO) r.getData("memberReceiveAddress", new TypeReference<MemberAddressVO>() {
        });
        if (data != null) {
            String phone = data.getPhone();
            String substring = phone.substring(phone.length() - 2, phone.length() - 1);
            BigDecimal price = new BigDecimal(substring);
            fareVO.setAddress(data);
            fareVO.setFare(price);
            return fareVO;
        }
        return null;
    }


}